package cn.niit.service.impl;

import cn.niit.dao.SysUserMapper;
import cn.niit.dao.SysUserRoleMapper;
import cn.niit.entity.Course;
import cn.niit.entity.SysUser;
import cn.niit.entity.query.SysUserQuery;
import cn.niit.enums.DelFlagEnum;
import cn.niit.service.SysUserService;
import cn.niit.utils.SaltUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@Service("sysUserService")
public class SysUserServiceImpl implements SysUserService {
    //添加Dao层的引用
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public PageInfo<SysUser> queryByUser(SysUserQuery sysUserQuery) {
        PageHelper.startPage(sysUserQuery.getPageNum(), sysUserQuery.getPageSize());
        return new PageInfo<SysUser>(sysUserMapper.queryByUser(sysUserQuery));
    }

    @Override
    public PageInfo<SysUser> queryByUserName(SysUserQuery sysUserQuery) {
        PageHelper.startPage(sysUserQuery.getPageNum(), sysUserQuery.getPageSize());
        return new PageInfo<SysUser>(sysUserMapper.queryByUserName(sysUserQuery));
    }

    @Override
    public PageInfo<SysUser> select(SysUserQuery sysUserQuery) {
        PageHelper.startPage(sysUserQuery.getPageNum(), sysUserQuery.getPageSize());
        return new PageInfo<SysUser>(sysUserMapper.select(sysUserQuery));
    }

    @Override
    public boolean editUser(SysUser sysUser) {
        int i = sysUserMapper.editUser(sysUser);
        return i > 0;
    }

    @Override
    public SysUser queryUserById(Long id) {
        return sysUserMapper.queryUserById(id);
    }


    /**
     * 注册用户
     * @param sysUser
     * @return
     */
    @Override
    public boolean addUser(SysUser sysUser) {
        /** 生成随机盐 */
        String userSalt = SaltUtils.getSalt();
        sysUser.setUserSalt(userSalt);
        /** 明文密码进行MD5 + Salt + hash 散列 */
        sysUser.setPassword(new Md5Hash(sysUser.getPassword(), SaltUtils.PUBLIC_SALT + userSalt, 1024).toHex());
//        sysUser.setDelFlag(DelFlagEnum.FALSE.getValue());   //默认未删除
//        sysUser.setCreateUserId(0L);
//        sysUser.setCreateUserName(sysUser.getUserName());
//        sysUser.setGmtCreate(new Date());
        int rows = sysUserMapper.addUser(sysUser);
        log.info("sysUser = {}", sysUser);
        return rows>0;
    }

    @Override
    public boolean deleteUserById(Long id) {
        int i = sysUserMapper.deleteUserById(id);
        return i > 0;
    }

    @Override
    public SysUser selectByUserCode(String userCode) {
        return sysUserMapper.getByUserCode(userCode);
    }

}
